const util = require('../../../utils/UmfUtils.js');
const constants = require('../../../common/Constants.js');
const PageRouter = require('../../../utils/PageRouter.js');
import * as cacheUtils from '../../../model/CacheUtils';
//点击提交按钮是否可以返回
let canBackLastPage = false;
//缓存状态
let cacheState = "";
export function pageSubmit(Toptips, errorMsg) {
  if (errorMsg) {
    Toptips.error({ text: errorMsg });
  } else {
    canBackLastPage = true;
    //没有修改数据 或者 缓存完成 后点击提交按钮
    if (!cacheState || cacheState == "1") {
      wx.navigateBack({ delta: 1 });
    } else {
      //缓存延时
      wx.showLoading();
    }
  }
}


/**
 * 缓存统一处理
 * @param params
 * @param flag
 */
export function cacheStorage(pageObj, storeId) {
  cacheState = "0";
  canBackLastPage = false;
  let cacheManager = pageObj["cacheManager"];
  //缓存本地
  cacheManager.cacheFunc(pageObj["params"]);
  let storageLen = cacheManager.storage ? Object.getOwnPropertyNames(cacheManager.storage).length : 0;
  let flag = constants.PosInfoSteps.STEP_NO_INFO.code;
  if (storageLen>0){
    flag = constants.PosInfoSteps.STEP_NO_COMPLETE.code;
  }
  if (isHaveInputData(cacheManager.storage)) {
    if (storageLen < pageObj["minLength"]) {
      //缓存未满
      flag = constants.PosInfoSteps.STEP_NO_COMPLETE.code;
    } else {
      //缓存已满
      let errorMsg = pageObj["page"]._checkForm(cacheManager.storage);
      // 数据不为空正则校验
      if (errorMsg) {
        flag = constants.PosInfoSteps.STEP_NO_COMPLETE.code;
      } else {
        flag = constants.PosInfoSteps.STEP_COMPLETE.code;
      }
    }
  }
  flagCacheStroage("basisInfo" + storeId, constants.STORAGE_FUNC.BASIS_INFO, { [pageObj["pageName"]]: flag }, function (callback) {
    cacheState = "1";
    //点击提交按钮  缓存成功 返回上一级页面
    if (canBackLastPage) {
      wx.hideLoading();
      wx.navigateBack({ delta: 1 });
    }
  });
}

export function flagCacheStroage(key, func, params, callback) {
  let app = getApp();
  key =  app.globalData.userData.agentId + app.globalData.userData.userId+ key;
  wx.getStorage({
    key: key,
    success: function (res) {
      let data = res.data;
      if (data[func]) {
        data[func] = Object.assign(data[func], params);
      } else {
        data[func] = params;
      }

      wx.setStorage({
        key: key,
        data: data,
        success: function (res) {
          callback(true);
        }
      });
    },

    fail: function () {
      let data = {
        [func]: params
      };
      wx.setStorage({
        key: key,
        data: data,
        success: function (res) {
          callback(true);
        }
      });
    }
  });
}

function isHaveInputData(formData) {
    for (var p in formData) {
        if (formData[p].length > 0) {

            return true;
        }
    }
    return false;
}